<template>
  <basic-dialog
    title="选择产地"
    width="60%"
    :visible="dialogVisible"
    :handleClose="handleCancel"
    :showFooter="false"
  >
    <el-card shadow="never" class="place_header_wrap">
      <el-row type="flex" align="middle" class="place_cascader_wrap">
        <i class="el-icon-position primary_color"></i>
        <p class="primary_color">产地选择</p>
        <el-cascader
          ref="cascader"
          v-model="cascaderValue"
          :props="cascaderProps"
          :disabled="isAbroad()"
          @change="handleChoosePlaceByCascader"
        ></el-cascader>
      </el-row>
      <el-row type="flex" align="middle" class="place_abroad_wrap">
        <el-checkbox v-model="abroadInfo.checkState">国外</el-checkbox>
        <el-input
          class="abroad_input"
          v-model.trim="abroadInfo.label"
          :disabled="!isAbroad()"
        ></el-input>
        <el-button
          type="primary"
          :disabled="!isAbroad()"
          @click="handleDetermineByAbroad"
        >确定</el-button
        >
      </el-row>
    </el-card>
    <el-card shadow="never">
      <BasicForm
        ref="formData"
        class="place_form_wrap"
        formItemWidth="60px"
        actionPosition="start"
        :isScalingBtn="false"
        :hasQueryPermission="false"
        :formColumns="formItemList"
        :dataSource="formData"
        :allDisabled="isAbroad()"
        :handleSearchForm="getTableDataBySearchForm"
        @getFormData="getFormData"
      />
      <BasicTable
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :tableHeight="480"
        :showActionCol="true"
        :actionRender="renderTableBtnAction"
        :showSelectCol="false"
        :pagination="pagination"
        :pageSizes="pageSizes"
        paginationPosition="center"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      />
    </el-card>
  </basic-dialog>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import BasicDialog from '@/components/BasicDialog';
import BasicForm from '@/components/BasicForm';
import BasicTable from '@/components/BasicTable';
import { isResponseSuccess } from '@/utils/bizUtils';
export default {
  components: {
    BasicDialog,
    BasicForm,
    BasicTable
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      dialogVisible: false,
      abroadInfo: {
        checkState: false, // 是否是国外
        label: '', // 名称
        value: 'ABROAD', // 固定value值（国外编码）
      },
      formData: {
        cityName: '', // 市
        areaName: '', // 区/县
      },
      formItemList: [
        { label: '市', prop: 'cityName', type: 'input' },
        { label: '区/县', prop: 'areaName', type: 'input' }
      ],
      cascaderProps: {
        lazy: true,
        lazyLoad: this.loadCascader,
        value: 'addressCode',
        label: 'addressName'
      },
      cascaderValue: [],
      firstOptions: [],
      tableInfo: {
        list: [],
        columns: [
          {
            title: '省',
            key: 'level1AddressName'
          },
          {
            title: '市',
            key: 'level2AddressName'
          },
          {
            title: '区/县',
            key: 'level3AddressName'
          }
        ],
        loading: false
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 10,
      },
      pageSizes: [10, 20, 30, 40],
      originalPlace: { // 最终选择返回给页面的结果
        producingAreaCode: '',
        producingAreaName: ''
      },
      apiObj: {
        getNextLevelAddressPager: { // 级联选择接口
          url: '/sysback/address/getNextLevelAddressPager',
          type: 'post'
        },
        getAddressPagerByName: { // 获取表格数据接口
          url: '/sysback/address/getAddressPagerByName',
          type: 'post'
        }
      }
    }
  },
  watch: {
    visible (val) {
      this.dialogVisible = val;
    }
  },
  methods: {
    // 当前表单为空
    isEmptyForForm () {
      const values = Object.values(this.formData);
      return values.every(item => !item);
    },
    // 是国外
    isAbroad () {
      return this.abroadInfo.checkState;
    },
    async loadCascader (node, resolve) {
      const { data, level } = node;
      const list = await this.getAddressByNextLevel(level, data?.addressCode);
      if (level === 2) {
        this.setOriginalPlace(data);
      }
      resolve(list);
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      return (<div class="table-action">
        {<el-button
          size="mini"
          type="text"
          disabled={ this.isAbroad() }
          onClick={() => this.handleChoosePlaceByTable({
            producingAreaCode: row.level2AddressCode,
            producingAreaName: row.level2AddressName
          })}
        >选择</el-button>}
      </div>);
    },
    // 给父组件发送所选产地信息
    emitOriginalPlace (data) {
      this.$emit('getOriginalPlace', data);
    },
    // 关闭弹框
    closeDialog () {
      this.$emit('update:visible', false);
    },
    // 清空所有状态
    clearAllState () {
      this.tableInfo.list = []; // 清空表格
      this.pagination = { // 重置分页
        nowPage: 1,
        totalNum: 0,
        pageShow: 10,
      }
      this.$refs.formData.handleResetForm(); // 清空表单
      // 重置cascader
      this.cascaderValue = [];
      this.$refs.cascader.panel.loadCount = 0;
      this.$refs.cascader.panel.lazyLoad();
      // 清空国外相关状态
      this.abroadInfo.label = '';
      this.abroadInfo.checkState = false;
    },
    // 设置所选产地数据
    setOriginalPlace ({ addressCode, addressName }) {
      this.originalPlace = {
        producingAreaCode: addressCode,
        producingAreaName: addressName
      }
    },
    // 获取表单内容
    getFormData (data) {
      this.formData = data;
    },
    // 获取表格数据 by 查询表单
    getTableDataBySearchForm () {
      if (this.isEmptyForForm()) {
        return this.$message.warning('请输入查询条件');
      }
      const { cityName, areaName } = this.formData;
      // 区/县 优先级高于 市，当有区县时，优先查区县
      this.postRequestTableData({
        ...this.apiObj.getAddressPagerByName,
        data: {
          addressLevel: areaName ? '103' : '102',
          addressNameLike: areaName || cityName,
          pageShow: this.pagination.pageShow,
          nowPage: this.pagination.nowPage
        }
      }).then(retData => {
        if (retData) {
          this.tableInfo.list = retData.results;
          this.pagination.totalNum = retData.totalNum;
        }
      });
    },
    // 根据地址等级查询地址信息
    async getAddressByNextLevel (level, addressCode) {
      const retData = await this.postRequestCascader({
        ...this.apiObj.getNextLevelAddressPager,
        data: {
          parentAddressCode: addressCode || '0',
          pageShow: 1000,
          nowPage: 1
        }
      });
      if (retData) {
        return retData.results.map(item => { return { ...item, leaf: level === 2 } });
      }
    },
    // 选择产地 by 表格操作栏
    handleChoosePlaceByTable (data) {
      this.emitOriginalPlace(data);
      this.closeDialog();
      this.clearAllState();
    },
    // 选择产地 by 级联选择框
    handleChoosePlaceByCascader () {
      this.emitOriginalPlace(this.originalPlace);
      this.closeDialog();
      this.clearAllState();
    },
    // 确定产地为国外
    handleDetermineByAbroad () {
      if (!this.abroadInfo.label) {
        return this.$message.warning('请输入国外的名称');
      }
      const data = {
        producingAreaCode: this.abroadInfo.value,
        producingAreaName: this.abroadInfo.label
      }
      this.emitOriginalPlace(data);
      this.closeDialog();
      this.clearAllState();
    },
    // 取消（仅关闭弹框）
    handleCancel () {
      this.closeDialog();
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.getTableDataBySearchForm();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.getTableDataBySearchForm();
    },
    // 级联选择post请求
    async postRequestCascader ({ url, type, data = {}, isFormData = false }) {
      const res = await ApiRequest(url, type, data, isFormData);
      if (isResponseSuccess(res)) {
        return res.retData;
      }
    },
    // 表格post请求
    async postRequestTableData ({ url, type, data = {}, isFormData = false }) {
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          return res.retData;
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    }
  }
}
</script>
<style lang="less" scoped>
.place_header_wrap {
  margin-bottom: 10px;
  .place_cascader_wrap {
    margin-bottom: 10px;
    p {
      min-width: 60px;
      margin-right: 10px;
    }
  }
  .abroad_input {
    width: 210px;
    margin: 0 10px;
  }
}
.place_form_wrap {
  margin-bottom: 10px;
  /deep/ .table-action {
    margin-left: 10px;
  }
}
</style>
